package org.company.mars.mina;

import java.io.Serializable;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;

public class CatHandler extends IoHandlerAdapter {
	
	private ConcurrentHashMap<Serializable, IoSession> map;
	
	@Override
	public void sessionCreated(IoSession session) throws Exception {
		System.out.println("created");
	}
	
	@Override
	public void sessionIdle(IoSession session, IdleStatus status)
			throws Exception {
		session.write("I'm a goodbaby,my sid = " + session.getId());
	}
	
	@Override
	public void sessionOpened(IoSession session) throws Exception {
		System.out.println("open");
		System.out.println(session.getId());
		session.setAttribute("init",Boolean.FALSE);
		session.write("already go");
	}
	
	@Override
	public void sessionClosed(IoSession session) throws Exception {
		System.out.println("closed");
	}
	
	protected synchronized Serializable doInit(IoSession session,Object message) {
		return null;
	}
	
	protected void onReceived(String message) {
		
	}
	
	/**
	 * 下发指令
	 * @param key
	 * @param msg
	 */
	public void send(Serializable key,String msg) {
		IoSession session = map.get(key);
		session.write(msg);
	}
	
	@Override
	public void messageReceived(IoSession session, Object message)
			throws Exception {
		
		onReceived((String)message);
	}
	
	@Override
	public void exceptionCaught(IoSession session, Throwable cause)
			throws Exception {
		session.close(false);
	}
}
